package com.itcaius.weblog.admin.service.Impl;

import com.itcaius.weblog.admin.model.vo.user.FindUserInfoRspVO;
import com.itcaius.weblog.admin.model.vo.user.UpdateAdminUserPasswordReqVo;
import com.itcaius.weblog.admin.service.AdminUserService;
import com.itcaius.weblog.common.domain.mapper.UserMapper;
import com.itcaius.weblog.common.enums.ResponseCodeEnum;
import com.itcaius.weblog.common.utils.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * @author Caius
 * @description
 * @since Created in 2025-04-21
 */
@Service
public class AdminUserServiceImpl implements AdminUserService {

    @Autowired
    private UserMapper userMapper;
   @Autowired
   private PasswordEncoder passwordEncoder;

    @Override
    public Response updatePassword(UpdateAdminUserPasswordReqVo updateAdminUserPasswordReqVo) {
        String username = updateAdminUserPasswordReqVo.getUsername();
        String password = updateAdminUserPasswordReqVo.getPassword();

        String encodePassword = passwordEncoder.encode(password);

        int count = userMapper.updatePasswordByUsername(username, encodePassword);

        return count == 1 ? Response.success() : Response.fail(ResponseCodeEnum.USERNAME_NOT_FOUND);
    }

    /**
     * 返回当前登录用户的信息
     * @return
     */
    @Override
    public Response findUserInfo() {
        // 获取 TreadLocal 中间的用户信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        String username = authentication.getName();

        return Response.success(FindUserInfoRspVO.builder().username(username).build());
    }
}
